package org.ipmsg.core.net;

import org.ipmsg.core.Message;
import java.io.IOException;
import java.net.*;
import java.util.ArrayList;

public class BroadcastSend extends Thread {

    private DatagramSocket udpSocket;
    private Message message;
    private ArrayList broadcastAddress;
    private int port;

    @Override
    public void run() {
        byte bytes[] = message.getBytes();
        try {
            InetAddress address = InetAddress.getByName("255.255.255.255");
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, port);
            udpSocket.send(packet);
        } catch (NoRouteToHostException ex) {
            try {
                InetAddress address = InetAddress.getByName("127.0.0.1");
                DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, port);
                udpSocket.send(packet);
            } catch (Exception exception) {
            }
            return;
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        if (broadcastAddress == null) {
            return;
        }
        for (int i = 0; i < broadcastAddress.size(); i++) {
            InetAddress address = (InetAddress) broadcastAddress.get(i);
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, port);
            try {
                udpSocket.send(packet);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }

    public BroadcastSend(DatagramSocket udpSocket, Message message, ArrayList broadcastAddress, int port) {
        this.udpSocket = udpSocket;
        this.message = message;
        this.broadcastAddress = broadcastAddress;
        this.port = port;
        start();
    }
}
